import { createStore } from 'vuex';
import korean from '../data/korean.json'

const store = createStore({
    state: {
        wordType: 'korean', // 单词类型
        wordTypeName: '韩语', // 单词类型
        eyeStatus: true, // 是否查看状态
        writeType: '1', // 默写类型2-中文 1-其他
        isAudio: true, // 朗读模式
        currentIndex: 1, // 当前展示下标
        wordLength: 50, 
        isStatus: 1, // 1-开始状态 2-结束状态
		fileList: [], // 词库列表
        dataList: {
            "korean": korean
        },
        nowWordList: [],
        errorWordList: []
    },
    getters: {
        wordList: (state) => {
            return state.nowWordList
        },
        nowWordObj: (state) => {
            return state.nowWordList[state.currentIndex-1] || {}
        }
    },
    mutations: {
        nextWord(state) {
            state.currentIndex++;
        },
        previousWord(state) {
            state.currentIndex--;
        },
        reset(state) {
            const getRandomSubset = (arr, size) => {
                return arr.sort(() => Math.random() - 0.5).slice(0, size);
            }
            const randomSubset = getRandomSubset(state.dataList[state.wordType], state.wordLength);
            state.nowWordList = randomSubset
            state.currentIndex = 1;
        },
        changeState(state, name) {
            name && (state[name] = !state[name])
        },
        changeWriteType(state, value) {
            state.writeType =  value
            state.nowWordList[state.currentIndex-1].writeType = ''
        },
		initWordList(state, value) {
			state.fileList = value || []
			// 默认选择第一个词库
			state.fileList[0].isSelected = true
		}
    },
    actions: {
        // 切换语言
        reset({ commit }) {
            commit('reset')
        },
        nextWord({ commit }) {
            commit('nextWord')
        },
        previousWord({ commit }) {
            commit('previousWord')
        },
        changeState({ commit }, name, value) {
            commit('changeState', name, value)
        },
        changeWriteType({ commit }, value) {
            commit('changeWriteType', value)
        },
		// 获取词库列表
		getWordList({ commit }, value) {
			$axios.request({
			     method: 'GET',
			     url: '/jsonData/fileList.json'
			 }).then(res => {
				 commit('initWordList', res.data)
			})
		}
    },
});

export default store;